package com.baize.filedowndemo.autoupdate

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import com.baize.filedowndemo.App

class VerifyVersionWorker(context: Context, parameters: WorkerParameters) :
  CoroutineWorker(context, parameters) {
  override suspend fun doWork(): Result {
    return try {
      val sharePreferences =
        App.getApplication().getSharedPreferences("download_config", Context.MODE_PRIVATE)
      val needUpload = sharePreferences.getBoolean("version", true) //模拟 是否需要更新
      val outputData = if (needUpload) {
        workDataOf(KEY_URL to DOWNLOAD_APK_URL)
      } else {
        workDataOf(KEY_URL to null)
      }
      //worker本身运行于子线程，方便就直接用了 //      val versionInfo = NetWork.getVersionInfo() // AppUtils.compareVersion()算法可以查询老的下载示例
      //      val outputData =
      //        if (versionInfo.versionCode > AppUtils.getAppVersionCode() || AppUtils.compareVersion(
      //            versionInfo.versionName, AppUtils.getAppVersionName()
      //          ) == 1
      //        ) {
      //          workDataOf(KEY_URL to versionInfo.url)
      //        } else { //公司工控屏是安卓6.0，所以还用getExternalStoragePublicDirectory
      //          val file =
      //            File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path) //如果最新版本 清空下载目录，url传null给下一个（手机app别这么干）
      //          val walk = file.walk()
      //          walk.iterator().forEach { file ->
      //            if (file.isFile) {
      //              file.delete()
      //            }
      //          }
      //          workDataOf(KEY_URL to null)
      //        }
      Result.success(outputData)
    } catch (e: Exception) {
      e.printStackTrace() //失败会启动WorkManager重试策略
      Result.failure()
    }
  }
}
